import { QL } from 'iflux2'
import { Map } from 'immutable'
const transform2Tree = (section) => {
    return Map({ 
        key: section.get('id'),
        value: String(section.get('id')),
        label:section.get('sname'),
    });
}
/**
 * 顶层系统栏目筛选
 */
export const topSectionsQL = QL("topSectionsQL",[
    'sections',
    (sections)=>sections.filter(item=>item.get('pid') == 0)
]);

/**
 * 组合ql，包含子栏目的合并到topsections的children字段里
 * @type {iflux2.QueryLang}
 */
export const tableSectionsQL = QL("tableSectionsQL",[
    topSectionsQL,
    'sections',
    (topSectionsQL,sections)=>{
        //按pid分组，数组的值本身就是数组
        let subSections = sections
                            .sortBy(sec => sec.get('sort'))//全局排序
                            .filter(item => item.get('pid') != 0)//过滤掉一级菜单
                            .groupBy(section =>section.get('pid'));//分组
        return topSectionsQL.map(sc => {
            if(subSections.has(sc.get('id'))){
                return sc.set('children',subSections.get(sc.get('id')));
            }
            return sc;
        })
    }
]);

export const treeSectionsQL = QL("treeSectionsQL",[
    topSectionsQL,
    'sections',
    (topSectionsQL,sections)=>{
        let subSections = sections.filter(item => item.get('pid') != 0).groupBy(section =>section.get('pid'));
        return topSectionsQL.map(sc => {
            if(subSections.has(sc.get('id'))){
                return transform2Tree(sc).set('children',subSections.get(sc.get('id')).map((sub)=>transform2Tree(sub)));
            }
            return transform2Tree(sc);
        })
    }
]);